<?php

namespace App\CustHub\Controller;

use App\Common\Constants\StorageModeConstants;
use App\CustHub\Annotation\ApiAuth;
use App\CustHub\Annotation\VerifySignature;
use App\System\Request\UploadRequest;
use App\System\Service\SystemUploadFileService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;

#[Controller(prefix: 'ch/upload'),ApiAuth]
class UploadController extends BaseController
{
    #[Inject]
    protected SystemUploadFileService $service;

    #[PostMapping('uploadFile')]
    public function uploadFile(UploadRequest $request): ResponseInterface
    {
        if ($request->validated() && $request->file('file')->isValid()) {
            $data = $this->service->upload(
                $request->file('file'),
                $request->all()
            );

            $url = $data['url'];
            if($data['storage_mode'] == StorageModeConstants::OSS){
                $data['url'] = config('file.storage.oss.domain','').$url;
            }

            return empty($data) ? $this->error() : $this->success($data);
        }
        return $this->error(t('system.upload_file_verification_fail'));
    }

    /**
     * 上传图片.
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping('uploadImage')]
    public function uploadImage(UploadRequest $request): ResponseInterface
    {
        if ($request->validated() && $request->file('image')->isValid()) {
            $data = $this->service->upload(
                $request->file('image'),
                $request->all()
            );
            $url = $data['url'];
            if($data['storage_mode'] == StorageModeConstants::OSS){
                $data['url'] = config('file.storage.oss.domain','').$url;
            }
            return empty($data) ? $this->error() : $this->success($data);
        }
        return $this->error(t('system.upload_image_verification_fail'));
    }
}